package com.lebang.controller.buss;

import com.alibaba.fastjson.JSONObject;
import com.lebang.common.Login;
import com.lebang.component.RedisClient;
import com.lebang.component.RedisSdkClient;
import com.lebang.domain.TaskRouse;
import com.lebang.entity.LbbFloatSwitch;
import com.lebang.entity.RequestHeaders;
import com.lebang.entity.member.LbbMember;
import com.lebang.entity.member.LbbMemberFeedback;
import com.lebang.model.MsgRequest;
import com.lebang.model.TaskRouseMemberVo;
import com.lebang.model.enums.Booleans;
import com.lebang.model.enums.buss.Reply;
import com.lebang.model.enums.buss.TaskCategory;
import com.lebang.model.enums.buss.TaskStatus;
import com.lebang.model.enums.buss.UserStatus;
import com.lebang.model.vo.buss.MemberFeedbackVo;
import com.lebang.model.vo.buss.MemberSearchVo;
import com.lebang.model.vo.buss.MemberTradeSearchVo;
import com.lebang.service.DownAppService;
import com.lebang.service.MemberNewTaskService;
import com.lebang.service.MemberWalletService;
import com.lebang.service.NewRouseService;
import com.lebang.service.buss.*;
import com.lebangweb.common.TextUtil;
import com.lebangweb.response.Callback;
import com.lebangweb.response.JsonData;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

import static com.lebang.controller.sys.MemberCashWithdrawalController.ALI_CASH_RECORD;
import static com.lebang.service.DownAppService.getSdkKey;

/**
 * 用户管理
 */
@Controller
public class MemberController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberTradeService memberTradeService;


    @Autowired
    private MemberFeedbackService memberFeedbackService;


    @Autowired
    private AppFloatSwitchService appFloatSwitchService;

    @Autowired
    private RedisClient redisClient;
    @Autowired
    private RedisSdkClient redisSdkClient;
    @Autowired
    private MemberNewTaskService newTaskService;
    @Autowired
    private MemberWalletService memberWalletService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private DownAppService downAppService;
    @Autowired
    private NewRouseService newRouseService;
    @Login
    @RequestMapping(value = {"/member/list"}, method = {RequestMethod.GET})
    public String members(Model model, HttpSession session) {
        return "/member/list";
    }

    @Login
    @RequestMapping(value = {"/member/getList"}, method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> list(MemberSearchVo vo) {
        Map<String, Object> data = memberService.list(vo);
        return data;
    }


    @Login
    @RequestMapping(value = {"/member/tradeList/{memberId}"}, method = {RequestMethod.GET})
    public String trades(@PathVariable String memberId, Model model) {
        model.addAttribute("memberId", memberId);
        return "/member/trade_list";
    }

    @Login
    @RequestMapping(value = {"/member/getTradeList"}, method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> tradeList(MemberTradeSearchVo vo) {
        return memberTradeService.list(vo);
    }

    @Login
    @RequestMapping(value = {"/member/recordList/{memberId}"}, method = {RequestMethod.GET})
    public String recordList(@PathVariable String memberId, Model model) {
        model.addAttribute("memberId", memberId);
        model.addAttribute("TaskCategory", TaskCategory.values());
        model.addAttribute("TaskStatus", TaskStatus.values());
        return "/member/record_list";
    }


    @Login
    @RequestMapping(value = {"/member/feedback_list"}, method = {RequestMethod.GET})
    public String feedbackList(Model model) {
        model.addAttribute("Reply", Reply.values());
        return "/member/feedback_list";
    }

    @Login
    @RequestMapping(value = {"/member/getFeedbackList"}, method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> getFeedbackList(MemberFeedbackVo vo) {
        Map<String, Object> data = memberFeedbackService.list(vo);
        return data;
    }

    @Login
    @RequestMapping(value = {"/member/reply"}, method = {RequestMethod.POST})
    @ResponseBody
    public String reply(@RequestParam(value = "feedbackId", required = false) String feedbackId,
                        @RequestParam(value = "result") String result,
                        HttpSession session) {
        Date time = new Date();
        LbbMemberFeedback mf = memberFeedbackService.getByFeedBackId(feedbackId);
        if (mf.getFeedbackId() == null || "".equals(mf.getFeedbackId())) {
            return "查无此号";
        } else {
            mf.setModifyTime(time);
            mf.setStatus(Booleans.True);
            mf.setResult(result);
        }
        //数据写入数据库
        memberFeedbackService.updateByPrimaryKeySelective(mf);
        //给用户提示消息     回馈编号，是否已回馈，回馈消息
        memberService.notice(mf, "反馈通知", "您的反馈有新的回复!");
        return "回复成功";
    }

    @Login
    @RequestMapping(value = "/member/detail", method = {RequestMethod.POST})
    @ResponseBody
    public Object detail(@RequestParam(value = "feedbackId") String feedbackId) {
        LbbMemberFeedback record = memberFeedbackService.getByFeedBackId(feedbackId);
        if (record == null) {
            return "记录不存在！";
        }
        return record;
    }

    @Login
    @RequestMapping(value = {"/member/show_list"}, method = {RequestMethod.GET})
    public String showList(Model model) {
        LbbFloatSwitch afs = appFloatSwitchService.getByCategory("floatSwitch");
        model.addAttribute("Reply", Reply.values());
        model.addAttribute("afs", afs);
        return "/member/show_list";
    }


    @PostMapping("/member/status")
    @Login
    @ResponseBody
    public JsonData status(String memberId, Integer status) {
        LbbMember member = memberService.selectMemberById(memberId);
        if (member == null) {
            return Callback.fail("fail", "操作失败", null);
        }
        if (status.equals(1)) {
            member.setStatus(UserStatus.Unusual.name());
        } else {
            member.setStatus("");
        }
        int t = memberService.updateMemberById(member);
        if (t == 1) {
            return Callback.success("success", "操作成功", null);
        } else {
            return Callback.fail("fail", "操作失败", null);
        }

    }

    @GetMapping("/member/sendmsg")
    @Login
    public String sendMsg(Model model) {
        return "/sendmsg/list";
    }

    @Login
    @GetMapping("/member/records/list")
    public String record() {
        return "/sendmsg/newapi-record";
    }

    @PostMapping("/member/count")
    @ResponseBody
    public JsonData sendMsg(HttpServletRequest request, Integer page, Integer limit, Integer type, MsgRequest msgRequest) {
        if (!msgRequest.filter()) {
            return Callback.fail("200", "参数非法", null);
        }
        int i = memberService.findCountByType(msgRequest);
        return Callback.success("200", "操作成功", i);
    }

    @PostMapping("/member/send")
    @ResponseBody
    public JsonData sendMsg1(HttpServletRequest request, Integer type, MsgRequest msgRequest) {
        if (!msgRequest.filter()) {
            return Callback.fail("200", "参数非法", null);
        }
        boolean i = memberService.sendMsByType(msgRequest);
        return i ? Callback.success("success", "操作成功", null) : Callback.fail("fail", "操作失败", null);
    }

    @Login
    @PostMapping("/member/closeMemberstatus")
    @ResponseBody
    public JsonData closeMemberstatus(HttpServletRequest request, Integer id) {
        memberService.updateByMemberId(id, UserStatus.Close.name());
        return Callback.success("200", "操作成功用户将无法登陆");
    }

    @Login
    @GetMapping("/member/records/sfz")
    public String sfz(String memberId, Model model) {
        model.addAttribute("memberId", memberId);
        return "/member/idcard";
    }

    @Login
    @GetMapping("/member/imeiloginrecord")
    public String imeiloginrecord(String memberId, Model model) {
        model.addAttribute("memberId", memberId);
        return "/member/imeiloginrecord";
    }

    @Login
    @ResponseBody
    @PostMapping("/member/records/sfz")
    public JsonData sfz(String memberId, String idCard, String name) {
        if(!TextUtil.isEmpty(idCard)){
            memberService.updateIdCardByIdCard(idCard);
        }
        memberService.updateIdCard(memberId, idCard, name);
        return Callback.success("success", "操作成功", null);
    }

    @Login
    @ResponseBody
    @PostMapping("/member/cleanImeiLogin")
    public JsonData cleanImeiLogin(String memberId, String imei) {
        LbbMember member = memberService.selectMemberById(memberId);
        memberService.deleteImeiLoginRecord(member.getPhone(), imei);
        return Callback.success("success", "操作成功", null);
    }

    @Login
    @PostMapping("/member/deleteAliMark")
    @ResponseBody
    public JsonData deleteAliMark(HttpServletRequest request, String memberId) {
        redisClient.del(ALI_CASH_RECORD+":"+memberId);
        return Callback.success("200", "解除账号限制成功");
    }
    @Login
    @PostMapping("/member/cleanmemberearncount")
    @ResponseBody
    public JsonData cleanmemberearncount(HttpServletRequest request, String memberId) {
        downAppService.cleanCount(memberId);
        return Callback.success("200", "清除成功");
    }
    @Login
    @PostMapping("/member/selectmemberearncount")
    @ResponseBody
    public JSONObject selectmemberearncount(HttpServletRequest request, String memberId) {
        RequestHeaders headers=new RequestHeaders();
        headers.setUserid(memberId);
        LbbMember member=memberService.selectByMemberId(memberId);
        LocalDate date=memberService.selectCreateById(memberId).toLocalDate();
        boolean check=date.equals(LocalDate.now());
        headers.setImei(member.getImei());

        List<TaskRouseMemberVo> list=new ArrayList<>();
        List<TaskRouse> rouses=newRouseService.selectAll();
        rouses.forEach(s->{
            TaskRouseMemberVo vo=new TaskRouseMemberVo();
            vo.setSdkName(s.getTaskName());
            vo.setSdkKey(s.getSdkKey());
            vo.setMaxCount(s.getMaxCount());
            Optional<String> str = redisClient.Optionalhget(getSdkKey(s.getSdkKey()), headers.getUserid());
            Integer memberCount = str.map(Integer::parseInt).orElse(0);
            Optional<String> imei = redisSdkClient.Optionalhget(getSdkKey(s.getSdkKey()), headers.getImei());
            Integer imeiCount = imei.map(Integer::parseInt).orElse(0);
            vo.setMemberTodayCount(memberCount);
            vo.setImeiTodayCount(imeiCount);
            vo.setAllCount(downAppService.getAllCountBySdkKey(headers,s.getSdkKey()));
            if(check){
                vo.setMaxDayCount(s.getNewMaxDayCount());
            }else {
                vo.setMaxDayCount(s.getMaxDayCount());
            }
            list.add(vo);
        });
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("data",list);
        jsonObject.put("count", list.size());
        jsonObject.put("code", 0);
        return jsonObject;

    }
    @Login
    @GetMapping("/member/selectmemberearncount")
    public String JsonData(HttpServletRequest request, String memberId,Model model) {
        model.addAttribute("memberId",memberId);
        return "/tbmember/earn";
    }

    @Login
    @PostMapping("/member/earndays")
    @ResponseBody
    public JsonData earnday(String phone,Integer num){

            if(TextUtil.isEmpty(phone,num)){
                return Callback.fail("fail", "参数错误");
            }
            LbbMember lbbMember = memberService.selectByPhone(phone);
            if(lbbMember==null){
                return Callback.fail("fail", "用户不存在");
            }
            //每日必赚新手任务完成
            newTaskService.addMrbz(num, lbbMember.getMemberId());



        return Callback.success("success", "成功",null);
    }

    @Login
    @GetMapping("/member/dayearn")
    public String dayEarn(Model model) {
        return "/member/dayearn";
    }


//    @Login
//    @GetMapping("/member/updateNegativeMoney")
//    @ResponseBody
//    public JsonData updateNegativeMoney(String pa){
//        if(pa.equals("xmlb8888")){
//            List<MemberWallet> memberWalletList = memberWalletService.selectNegativeMoney();
//            memberWalletList.forEach(s->{
//                memberTradeService.walletClean(s.getMemberId());
//            });
//        }
//
//        return Callback.success("success", "成功",null);
//    }

    @Login
    @GetMapping("/member/newlist")
    public String list() {
        return "/tbmember/list";
    }


    @Login
    @ApiOperation(value = "分页")
    @PostMapping("/member/data")
    @ResponseBody
    public Map<String, Object> list(HttpServletRequest request,Long page, Integer limit,String search,String weixin,String alipay,String appId,String memberId) {
        if(TextUtil.isEmpty(search)){
            search = null;
        }
        if(TextUtil.isEmpty(weixin)){
            weixin = null;
        }
        if(TextUtil.isEmpty(alipay)){
            alipay = null;
        }
        if(TextUtil.isEmpty(appId)){
            appId = null;
        }
        if(TextUtil.isEmpty(memberId)){
            memberId = null;
        }
        Map<String, Object> returnMap = new HashMap<>();
        page = (page - 1) * limit;
        List<Map<String,String>> list =memberService.page(page,limit,search,weixin,alipay,appId,memberId);
        list.parallelStream().forEach(s->{
            Integer all = walletService.totalMoney(s.get("memberId"), s.get("appId"));
            Integer lift = walletService.cashMoney(s.get("memberId"), s.get("appId"));
            s.put("redisMoney",new BigDecimal(all - lift).divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN).toString());
        });
        returnMap.put("data",list);
        returnMap.put("count", memberService.count(search,weixin,alipay,appId,memberId));
        returnMap.put("code", 0);
        return returnMap;
    }


    @Login
    @PostMapping("/member/banall")
    @ResponseBody
    public JsonData banall(@RequestParam(name = "idlist", required = true) String idlist) {
        try {
            if (!TextUtil.isEmpty(idlist)) {

                List<String> list = Arrays.asList(idlist.split(","));
                int i = memberService.updateStatusByList(UserStatus.Close.name(),list);
                if (i > 0) {
                    return Callback.success("success", "操作成功", null);
                } else {
                    return Callback.fail("error", "操作失败", null);
                }
            } else {
                return Callback.fail("error", "参数异常", null);
            }
        } catch (Exception e) {
            return Callback.fail("error", "未知错误 ", e.getMessage());
        }
    }


    @Login
    @PostMapping("/member/pickall")
    @ResponseBody
    public JsonData pickall(@RequestParam(name = "idlist", required = true) String idlist) {
        try {
            if (!TextUtil.isEmpty(idlist)) {

                List<String> list = Arrays.asList(idlist.split(","));
                int i = memberService.updateStatusByList("",list);
                if (i > 0) {
                    return Callback.success("success", "操作成功", null);
                } else {
                    return Callback.fail("error", "操作失败", null);
                }
            } else {
                return Callback.fail("error", "参数异常", null);
            }
        } catch (Exception e) {
            return Callback.fail("error", "未知错误 ", e.getMessage());
        }
    }


}